package com.demo.test.file;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ReturnFile {


    //接收http请求并将需要的文件打包返回
    public void mark(HttpServletResponse response) {
        OutputStream out = null;
        ZipOutputStream zos = null;
        try {
            response.setContentType("multipart/form-data");
            //获取要打包的多个文件
            File file1 = new File("C:/Users/xhc/Desktop/a/spring-quartz.xml");
            File file2 = new File("C:/Users/xhc/Desktop/a/spring-servlet.xml");
            List<File> fileList = new ArrayList<>();
            fileList.add(file1);
            fileList.add(file2);
            out = response.getOutputStream();
            zos = new ZipOutputStream(out);
            for (File file : fileList) {
                ZipEntry entry = new ZipEntry(file.getName());
                zos.putNextEntry(entry);
                byte [] bytes = new byte[1024];
                int len;
                FileInputStream in = new FileInputStream(file);
                while((len = in.read(bytes)) != -1) {
                    zos.write(bytes, 0, len);
                }
                zos.closeEntry();
                in.close();
            }

        } catch (Exception e) {

        }finally {
            if(zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
